package com.woniuxy.juc.cas;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 原子引用类型
 * <P> Date: 2022/4/9:12:38
 * <P> Description:
 */

public class AtomicReferenceTest {
    public static void main(String[] args) {
        Account account = new AccountReference(new BigDecimal(10000));
        Account.demo(account);

    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class AccountReference implements Account {

        /**
         * TODO 使用原子引用类型 维护一个对象
         */
        private AtomicReference<BigDecimal> balance;

        public AccountReference(BigDecimal balance) {
            this.balance = new AtomicReference(balance);
        }

        @Override
        public BigDecimal getBalance() {
            return this.balance.get();
        }

        @Override
        public void withdraw(BigDecimal amount) {
            while (true) {
                BigDecimal prev = this.balance.get();
                BigDecimal next = prev.subtract(amount);
                if (balance.compareAndSet(prev, next)) {
                    break;
                }
            }
        }
    }


    interface Account {
        // TODO 获取余额
        BigDecimal getBalance();

        // TODO 取款
        void withdraw(BigDecimal amount);

        /**
         * TODO 方法内会启动 1000 个线程，每个线程做 -10 元 的操作
         *  如果初始余额为 10000 那么正确的结果应当是 0
         */
        static void demo(Account account) {
            List<Thread> ts = new ArrayList<>();
            long start = System.nanoTime();
            for (int i = 0; i < 1000; i++) {
                ts.add(new Thread(() -> {
                    account.withdraw(new BigDecimal(10));
                }));
            }
            ts.forEach(Thread::start);
            ts.forEach(t -> {
                try {
                    t.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            long end = System.nanoTime();
            System.out.println(account.getBalance()
                    + " cost: " + (end - start) / 1000_000 + " ms");
        }
    }

}
